import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import 'element-plus/theme-chalk/display.css'
import scui from './scui'
import i18n from './locales'
import router from './router'
import store from './store'
import App from './App.vue'

// 自定义指令拖动
const draggableDirective = {
  mounted(el) {
    const dialogHeader = el.querySelector('.el-dialog__header');
    const dialog = el.querySelector('.el-dialog');
    let isDragging = false;
    let offsetX = 0, offsetY = 0;

    dialogHeader.style.cursor = 'move';

    dialogHeader.addEventListener('mousedown', (e) => {
      isDragging = true;
      const rect = dialog.getBoundingClientRect();
      offsetX = e.clientX - rect.left;
      offsetY = e.clientY - rect.top;
      dialog.style.userSelect = 'none'; // 防止拖动时选中文本
    });

    document.addEventListener('mousemove', (e) => {
      if (!isDragging) return;
      const x = e.clientX - offsetX;
      const y = e.clientY - offsetY;
      
      // 边界检查（防止拖出可视区域）
      const maxX = window.innerWidth - dialog.offsetWidth;
      const maxY = window.innerHeight - dialog.offsetHeight;
      dialog.style.left = `${Math.max(0, Math.min(x, maxX))}px`;
      dialog.style.top = `${Math.max(0, Math.min(y, maxY))}px`;
    });

    document.addEventListener('mouseup', () => {
      isDragging = false;
      dialog.style.userSelect = 'auto';
    });
  }
};
// 自定义防抖指令
const throttleClick = {
  beforeMount(el, binding, vnode) {
    const instance = vnode.componentInstance || vnode.ctx
    const defaultEvent = 'click'
    const defaultDelay = 500
    
    // 参数解析
    const params = {
      event: binding.arg || defaultEvent,
      delay: Object.keys(binding.modifiers)
        .reduce((acc, mod) => !isNaN(mod) ? parseInt(mod) : acc, defaultDelay),
      handler: null
    }

    // 处理不同传参形式
    if (typeof binding.value === 'function') {
      params.handler = binding.value
    } else if (binding.value?.handler) {
      Object.assign(params, binding.value)
    }

    if (!params.handler) {
      console.error('[v-debounce] 必须绑定有效的处理函数')
      return
    }

    // 防抖实现
    let timeoutId
    const debouncedFn = (...args) => {
      clearTimeout(timeoutId)
      timeoutId = setTimeout(() => {
        params.handler.apply(instance?.proxy, args)
      }, params.delay)
    }

    // 保存引用
    el._debounceConfig = {
      event: params.event,
      handler: debouncedFn,
      original: params.handler
    }

    // 添加事件监听
    el.addEventListener(params.event, debouncedFn)
  },

  unmounted(el) {
    if (el._debounceConfig) {
      el.removeEventListener(
        el._debounceConfig.event,
        el._debounceConfig.handler
      )
      delete el._debounceConfig
    }
  }
};
// 自定义指令缩放
const dialogResizeDirective = {
  mounted(el) {
    const resizeHandles = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'];
    const dragDom = el.querySelector('.el-dialog');

    if (!dragDom) return;

    // 创建并添加缩放手柄
    resizeHandles.forEach(handle => {
      const handleEl = document.createElement('div');
      handleEl.classList.add(`resize-handle-${handle}`);
      handleEl.style.cssText = `
        position: absolute;
        width: 10px;
        height: 10px;
        background-color: rgba(0, 0, 0, 0.2);
        cursor: ${handle}-resize;
      `;
      switch (handle) {
        case 'nw': handleEl.style.top = '0'; handleEl.style.left = '0'; break;
        case 'n': handleEl.style.top = '0'; handleEl.style.left = '50%'; handleEl.style.transform = 'translateX(-50%)'; break;
        case 'ne': handleEl.style.top = '0'; handleEl.style.right = '0'; break;
        case 'e': handleEl.style.top = '50%'; handleEl.style.right = '0'; handleEl.style.transform = 'translateY(-50%)'; break;
        case 'se': handleEl.style.bottom = '0'; handleEl.style.right = '0'; break;
        case 's': handleEl.style.bottom = '0'; handleEl.style.left = '50%'; handleEl.style.transform = 'translateX(-50%)'; break;
        case 'sw': handleEl.style.bottom = '0'; handleEl.style.left = '0'; break;
        case 'w': handleEl.style.top = '50%'; handleEl.style.left = '0'; handleEl.style.transform = 'translateY(-50%)'; break;
      }
      dragDom.appendChild(handleEl);

      handleEl.onmousedown = (e) => {
        const startWidth = parseFloat(getComputedStyle(dragDom).width);
        const startHeight = parseFloat(getComputedStyle(dragDom).height);
        const startX = e.clientX;
        const startY = e.clientY;

        document.onmousemove = (e) => {
          let newWidth = startWidth + (handle.includes('e') ? e.clientX - startX : handle.includes('w') ? startX - e.clientX : 0);
          let newHeight = startHeight + (handle.includes('s') ? e.clientY - startY : handle.includes('n') ? startY - e.clientY : 0);

          // 设置最小尺寸限制
          newWidth = Math.max(newWidth, 200);
          newHeight = Math.max(newHeight, 150);

          dragDom.style.width = `${newWidth}px`;
          dragDom.style.height = `${newHeight}px`;

          // 如果是顶部或左部调整，则需要改变位置
          if (handle.includes('n')) {
            dragDom.style.top = `${parseFloat(getComputedStyle(dragDom).top) + (startHeight - newHeight)}px`;
          }
          if (handle.includes('w')) {
            dragDom.style.left = `${parseFloat(getComputedStyle(dragDom).left) + (startWidth - newWidth)}px`;
          }
        };

        document.onmouseup = () => {
          document.onmousemove = null;
          document.onmouseup = null;
        };
      };
    });
  }
};

const app = createApp(App);
app.directive('draggable', draggableDirective);
app.directive('dialogResize', dialogResizeDirective);
app.directive('throttleClick', throttleClick);

app.use(store);
app.use(router);
app.use(ElementPlus);
app.use(i18n);
app.use(scui);

//挂载app
app.mount('#app');
